package com.apexsoft.front.common.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 与系统相关的一些常用工具方法.
 * 
 * @author stephen
 * @version 1.0.0
 */
public class SystemTool {
	
	private static final Logger LOGGER = LogManager.getRootLogger();
	/**
	 * 获取当前操作系统名称. return 操作系统名称 例如:windows xp,linux 等.
	 */
	public static String getOSName() {
		return System.getProperty("os.name").toLowerCase();
	}

	/**
	 * 获取unix网卡的mac地址. 非windows的系统默认调用本方法获取.如果有特殊系统请继续扩充新的取mac地址方法.
	 * 
	 * @return mac地址
	 */
	public static String getUnixMACAddress() {
		String mac = null;
		BufferedReader bufferedReader = null;
		Process process = null;
		try {
			process = Runtime.getRuntime().exec("ifconfig eth0");// linux下的命令，一般取eth0作为本地主网卡
																	// 显示信息中包含有mac地址信息
			bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String line = null;
			int index = -1;
			while ((line = bufferedReader.readLine()) != null) {
				index = line.toLowerCase().indexOf("hwaddr");// 寻找标示字符串[hwaddr]
				if (index >= 0) {// 找到了
					mac = line.substring(index + "hwaddr".length() + 1).trim();// 取出mac地址并去除2边空格
					break;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (bufferedReader != null) {
					bufferedReader.close();
				}
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			bufferedReader = null;
			process = null;
		}

		return mac;
	}

	/**
	 * 获取widnows网卡的mac地址.
	 * 
	 * @return mac地址
	 */
	public static String getWindowsMACAddress() {
		String mac = null;
		BufferedReader bufferedReader = null;
		Process process = null;
		try {
			process = Runtime.getRuntime().exec("ipconfig /all");// windows下的命令，显示信息中包含有mac地址信息
			bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String line = null;
			int index = -1;
			while ((line = bufferedReader.readLine()) != null) {
				index = line.toLowerCase().indexOf("physical address");// 寻找标示字符串[physical
																		// address]
				if (index >= 0) {// 找到了
					index = line.indexOf(":");// 寻找":"的位置
					if (index >= 0) {
						mac = line.substring(index + 1).trim();// 取出mac地址并去除2边空格
					}
					break;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (bufferedReader != null) {
					bufferedReader.close();
				}
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			bufferedReader = null;
			process = null;
		}

		return mac;
	}

	/**
	 * 测试用的main方法.
	 * 
	 * @param argc
	 *            运行参数.
	 */
	public static void main(String[] argc) {
		String os = getOSName();
		System.out.println(os);
		if (os.startsWith("windows")) {
			// 本地是windows
			String mac = getWindowsMACAddress();
			System.out.println(mac);
		} else {
			// 本地是非windows系统 一般就是unix
			String mac = getUnixMACAddress();
			System.out.println(mac);
		}
		
		System.out.println(getMacAddress("192.168.1.77"));
	}

	public static String getMac() {
		String os = getOSName();
		if (os.startsWith("windows")) {
			// 本地是windows
			String mac = getWindowsMACAddress();
			return mac;
		} else {
			// 本地是非windows系统 一般就是unix
			String mac = getUnixMACAddress();
			return mac;
		}
	}

	public static String getMacAddress(String host) {
		String mac = "";
		StringBuffer sb = new StringBuffer();

		try {
			NetworkInterface ni = NetworkInterface.getByInetAddress(InetAddress.getByName(host));

			byte[] macs = ni.getHardwareAddress();

			for (int i = 0; i < macs.length; i++) {
				mac = Integer.toHexString(macs[i] & 0xFF);

				if (mac.length() == 1) {
					mac = '0' + mac;
				}

				sb.append(mac + "-");
			}

		} catch (SocketException e) {
			e.printStackTrace();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}

		mac = sb.toString();
		mac = mac.substring(0, mac.length() - 1);

		return mac;
	}
	
	/**
	 * 获取客户端IP地址（兼容有反向代理的情况）
	 * @return
	 */
	public static String getIpAddr() { 
		HttpServletRequest request =  ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	    String ip = request.getHeader("x-forwarded-for"); 
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	        ip = request.getHeader("Proxy-Client-IP"); 
	    } 
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	        ip = request.getHeader("WL-Proxy-Client-IP"); 
	    } 
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	        ip = request.getRemoteAddr(); 
	    } 
	    return ip; 
	}
	/**
	 * 获取服务端IP地址
	 * @return
	 */
	public static String getServerIp() { 
	    String ip = ""; 
	    try {
	    	ip = InetAddress.getLocalHost().getHostAddress();//取服务器IP
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			ip = SystemTool.getIpAddr();//异常情况取客户机操作站点
		}
	    return ip; 
	}
	
	public static final int CLIENT_PC = 1;
	public static final int CLIENT_PC_IE = 2;
	public static final int CLIENT_PC_OPERA = 3;
	public static final int CLIENT_PC_MAC = 4;
	public static final int CLIENT_PC_FIREFOX = 5;
	public static final int CLIENT_MOBILE = 20;
	public static final int CLIENT_MOBILE_IPAD = 21;
	public static final int CLIENT_MOBILE_IPHONE = 22;
	public static final int CLIENT_MOBILE_ANDROID = 23;
	public static final int CLIENT_MOBILE_WINXIN = 24;
	public static final int CLIENT_MOBILE_XINETOU = 25;

	public static int getRequestClient(String userAgent) {
		if (userAgent.indexOf("MicroMessenger") >= 0 || userAgent.indexOf("micromessenger") >= 0) {
			// 是否为微信
			return CLIENT_MOBILE_WINXIN;
		} else if (userAgent.indexOf("iPad") >= 0) {
			// 是否为iPad
			return CLIENT_MOBILE_IPAD;
		} else if (userAgent.indexOf("iPhone") >= 0) {
			// Iphone
			return CLIENT_MOBILE_IPHONE;
		} else if (userAgent.indexOf("Android") >= 0 || userAgent.indexOf("Linux") >= 0) {
			// android
			return CLIENT_MOBILE_ANDROID;
		}
		if (userAgent.indexOf("MSIE") >= 0) {
			// IE内核
			return CLIENT_PC_IE;
		} else if (userAgent.indexOf("Presto") >= 0) {
			// opera内核
			return CLIENT_PC_OPERA;
		} else if (userAgent.indexOf("AppleWebKit") >= 0) {
			// 苹果、谷歌内核
			return CLIENT_PC_MAC;
		} else if (userAgent.indexOf("Gecko") >= 0 && userAgent.indexOf("KHTML") >= 0) {
			// 火狐内核
			return CLIENT_PC_FIREFOX;
		} else {
			return CLIENT_PC;
		}

	}
	
	public static String getRequestClientOsType() {
		HttpServletRequest request =  ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String userAgent = request.getHeader("user-agent");
		LOGGER.info("=========userAgent:"+userAgent);
		if (userAgent.indexOf("MicroMessenger") >= 0 || userAgent.indexOf("micromessenger") >= 0) {
			// 是否为微信
			return "weixin";
		} else if (userAgent.indexOf("iPad") >= 0) {
			// 是否为iPad
			return "ios";
		} else if (userAgent.indexOf("iPhone") >= 0) {
			// Iphone
			return "ios";
		} else if (userAgent.indexOf("Android") >= 0 || userAgent.indexOf("Linux") >= 0) {
			// android
			return "android";
		} else if (userAgent.indexOf("okhttp/3.4.1") >= 0) {
			// android
			return "android";
		}else {
			return "pc";
		}
	}
	public static String getRequestClientDeviceType() {
		HttpServletRequest request =  ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String userAgent = request.getHeader("user-agent");
		LOGGER.info("=========userAgent:"+userAgent);
		Pattern pattern = Pattern.compile(";\\s?(\\S*?\\s?\\S*?)\\s?(Build)?/");  
        Matcher matcher = pattern.matcher(userAgent);  
        String model = null;  
        if (matcher.find()) {  
            model = matcher.group(1).trim();  
        }  
		return model;
	}
	
}
